lobsterlayui.main(['index', 'layer', 'form', 'element', 'table', 'laydate', 'echarts'], {
    data: {
        table: null,
        tableoptions: {},
        layerindex: 0,
        chartdata: [],//图表数据 
        xdata: [],
        selectedindex: 0,
        ydata1: [],
        ydata1: [],
        tabledata: [],//表格数据
        data24: [],//近24小时数据
    },
    pageload: function (right) {
        console.log(right);
        var self = this;
        self.initevent();
        Promise.all([self.getchartdata(0)]).then(res => {
            var ydata1 = res[0].data.ydata1;
            self.data.data24 = res[0].data.ydata1;
            var ydata2 = res[0].data.ydata2;
            var total1 = self.sum(ydata1.map(n => parseFloat(n.TotalFee)));
            var total2 = self.sum(ydata2.map(n => parseFloat(n.TotalFee)));
            var num1 = self.sum(ydata1.map(n => parseFloat(n.num)));
            var num2 = self.sum(ydata2.map(n => parseFloat(n.num)));

            self.data.chartdata.push({
                ydata1: ydata1.map(n => { return { OrderDate: n.OrderDate, value: n.TotalFee } }),
                ydata2: ydata2.map(n => { return { OrderDate: n.OrderDate, value: n.TotalFee } }),
                value: total1,
                tongbi: (((total1 - total2) / total2) * 100).toFixed(2),
            })
            self.data.chartdata.push({
                ydata1: ydata1.map(n => { return { OrderDate: n.OrderDate, value: n.num } }),
                ydata2: ydata2.map(n => { return { OrderDate: n.OrderDate, value: n.num } }),
                value: num1,
                tongbi: num2 > 0 ? (((num1 - num2) / num2) * 100).toFixed(2) : 0,
            })
            var pingjun1 = Math.floor((total1 / num1 * 100)) / 100;
            var pingjun2 = Math.floor((total2 / num2 * 100)) / 100;
            self.data.chartdata.push({
                ydata1: ydata1.map(n => { return { OrderDate: n.OrderDate, value: n.TotalFee } }),
                ydata2: ydata2.map(n => { return { OrderDate: n.OrderDate, value: n.TotalFee } }),
                value: pingjun1,
                tongbi: pingjun2 > 0 ? (((pingjun1 - pingjun2) / pingjun2) * 100).toFixed(2) : 0,
            })
            self.sethead();
            self.setchart();
            self.settabledata();
            self.loaddata();
        })
    },

    //初始化事件
    initevent: function () {
        var self = this;
        $("#cont>div").click(function () {
            $("#cont>div").removeClass("selected");
            $(this).addClass("selected");
            self.data.selectedindex = $(this).data("index");
            self.setchart();
        })
        $("#toexcel").click(function () {
            var tabledata = self.data.tabledata;
            var head = ['#起止时间：' + tabledata[0].OrderDate.substring(0, 16) + ":00" + "-" + tabledata[tabledata.length - 1].OrderDate.substring(0, 16) + ":00"];
            var data = [];
            data.push(['销售金额总计(元)', '销售总笔数', '人均金额(元)']);
            var filtertabledata = self.data.tabledata.filter(a => { return a.TotalFee > 0 && a.Num > 0 });
            var totalsum = self.sum(filtertabledata.map(n => n.TotalFee));
            var numsum = self.sum(filtertabledata.map(n => n.Num));
            data.push([totalsum, numsum, (totalsum / numsum).toFixed(2)]);
            data.push([]);
            data.push(['时间', '销售金额(元)', '销售笔数', '人均金额']);
            self.data.tabledata.forEach(a => {
                if (a.TotalFee > 0 & a.Num > 0) {
                    data.push([a.OrderDate, a.TotalFee, a.Num, a.Pingjun]);
                }
            })
            layui.table.exportFile(head, data, 'csv'); //默认导出 csv，也可以为：xls
        })
        //监听行工具事件
        layui.table.on('tool(datatable)', function (obj) {  //tool是工具条事件名，table原始容器的属性
            var data = obj.data;//当前行数据
            var layEvent = obj.event;//获得lay-event的值
            var sdate = data.OrderDate.substring(0, 16) + ":00";
            var edate = data.OrderDate.substring(0, 11) + data.OrderDate.substring(17, 22) + ":00"
            if (obj.event === "detail") {
                window.open('pay.html?sdate=' + sdate + '&edate=' + edate)
            }

        });
    },
    //加载订单列表
    loaddata: function () {
        var self = this;
        var date = $("#date").val() || "";
        self.data.table = layui.table.render({
            elem: '#datatable',
            data: self.data.tabledata,
            // height: 'full-130',
            cellMinWidth: 80,
            size: 'sm',
            limit: 1000,
            cols: [[
                { width: "20%", field: 'OrderDate', title: '时间' },
                { width: "20%", field: 'TotalFee', title: '销售金额(元)' },
                { width: "20%", field: 'Num', title: '销售笔数(笔)' },
                { width: "20%", field: 'Pingjun', title: '人均金额(元)' },
                { title: '操作', toolbar: '#operation', width: '20%' }
            ]]
        })
    },
    getchartdata(type) {
        var self = this;
        return new Promise((resolve, reject) => {
            admin.req({
                type: "get",
                url: self.getbaseurl("pay.getchartdata"),
                data: {
                    type: type
                },
                done: function (res) {
                    resolve(res);
                }
            });
        })

    },
    loadchart: function (unit) {
        var self = this;
        var chartDom = document.getElementById('chart1');
        var myChart = echarts.init(chartDom);
        var option;
        option = {
            tooltip: {
                trigger: 'axis',
                formatter(params) {
                    var returnstr = "时间：" + params[0].name;
                    for (x in params) {
                        returnstr += "<br/>" + params[x][0] + params[x].value + ' (' + (self.data.selectedindex == 1 ? '笔' : '元') + ')';
                    }
                    return returnstr;
                }
            },
            legend: {
                data: ['近24小时', '上24小时']
            },
            toolbox: {
                show: true,
                feature: {
                    dataZoom: {
                        yAxisIndex: 'none'
                    },
                    dataView: { readOnly: false },
                    magicType: { type: ['line', 'bar'] },
                    restore: {},
                    saveAsImage: {}
                }
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: self.data.xdata
            },
            yAxis: {

            },
            series: [
                {
                    name: '近24小时',
                    type: 'line',
                    itemStyle: {
                        normal: {
                            color: '#009b40',
                            lineStyle: {
                                color: '#009b40'
                            }
                        }
                    },
                    data: self.data.ydata1,
                },
                {
                    name: '上24小时',
                    type: 'line',
                    itemStyle: {
                        normal: {
                            color: '#999999',
                            lineStyle: {
                                color: '#999999'
                            }
                        }
                    },
                    data: self.data.ydata2,
                }
            ]
        };
        option && myChart.setOption(option);
    },
    formatDate: function (date) {
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? '0' + m : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        var h = date.getHours();
        h = h < 10 ? ('0' + h) : h;
        var mm = date.getMinutes();
        mm = mm < 10 ? ('0' + mm) : mm;
        var s = date.getSeconds();
        s = s < 10 ? ('0' + s) : s;
        return y + '-' + m + '-' + d + ' ' + h + ':' + mm + ':' + s;
    },
    sethead() {
        var self = this;
        self.data.chartdata.forEach((a, index) => {
            $("#div" + index).text(a.value);
            if (a.tongbi > 0) {
                $("#img" + index).attr("src", "../image/up.png")
            } else {
                $("#img" + index).attr("src", "../image/down.png")
            }
            $("#label" + index).text(a.tongbi + '%');

        })
    },
    setchart() {
        var self = this;
        var now = new Date(self.formatDate(new Date()).substring(0, 13) + ':00:00');
        self.data.xdata = [];
        self.data.ydata1 = [];
        self.data.ydata2 = [];
        var ydata1 = self.data.chartdata[self.data.selectedindex].ydata1;
        var ydata2 = self.data.chartdata[self.data.selectedindex].ydata2;
        for (var i = 24; i >= 1; i--) {
            var sdate = new Date(now.getTime() - 60 * 60 * 1000 * i);
            var edate = new Date(sdate.getTime() + 60 * 60 * 1000);
            var dateformat = self.formatDate(sdate).substring(0, 13);
            var filter = ydata1.filter(a => { return a.OrderDate == dateformat });
            if (filter != null && filter.length > 0) {
                self.data.ydata1.push(parseFloat(filter[0].value));
            } else {
                self.data.ydata1.push(0)
            }
            sdate = new Date(now.getTime() - 60 * 60 * 1000 * (i + 24));
            dateformat = self.formatDate(sdate).substring(0, 13);
            filter = ydata2.filter(a => { return a.OrderDate == dateformat });
            if (filter != null && filter.length > 0) {
                self.data.ydata2.push(parseFloat(filter[0].value));
            } else {
                self.data.ydata2.push(0)
            }
            self.data.xdata.push(self.formatDate(sdate).substring(11, 13) + ':00' + '-' + self.formatDate(edate).substring(11, 13) + ':00');
        }
        self.loadchart();
    },
    settabledata() {
        var self = this;
        var now = new Date(self.formatDate(new Date()).substring(0, 13) + ':00:00');
        for (var i = 24; i >= 1; i--) {
            var sdate = new Date(now.getTime() - 60 * 60 * 1000 * i);
            var edate = new Date(sdate.getTime() + 60 * 60 * 1000);
            var dateformat = self.formatDate(sdate).substring(0, 13);
            var filter = self.data.data24.filter(a => { return a.OrderDate == dateformat });
            var totalfee = 0;
            var num = 0;
            var pinjun = 0;
            if (filter != null && filter.length > 0) {
                totalfee = parseFloat(filter[0].TotalFee);
                num = parseInt(filter[0].num);
                pinjun = (totalfee / num).toFixed(2);
            }
            self.data.tabledata.push({
                OrderDate: self.formatDate(sdate).substring(0, 13) + ':00-' + self.formatDate(edate).substring(11, 13) + ':00',
                TotalFee: totalfee,
                Num: num,
                Pingjun: pinjun,
            })
        }
        var jiezhidate = new Date(now.getTime() - 60 * 60 * 1000 * i);
        // 注：数据更新至2021年9月8日9点。
        var year = jiezhidate.getFullYear();
        var month = jiezhidate.getMonth() + 1;
        var day = jiezhidate.getDate();
        var hour = jiezhidate.getHours();
        $("#biaozhu").text("注：数据更新至" + year + "年" + month + "月" + day + "日" + hour + "点")

    },
    sum(arr) {
        var s = 0;
        arr.forEach(function (val, idx, arr) {
            s += val;
        }, 0);
        return s;
    },
})